// 账号管理
import { PageContainer } from '@ant-design/pro-components';
import {
  SearchOutlined,
  DeleteOutlined,
  EditOutlined,
  UndoOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { useModel } from '@umijs/max';
import {
  Input,
  Space,
  Button,
  Badge,
  Table,
  Modal,
  message,
  Form,
  Select,
  DatePicker,
  Row,
  Col,
  InputNumber,
  Typography,
  Pagination,
  Spin,
} from 'antd';
import type { GetProps, FormProps } from 'antd';
import type { TableProps, PaginationProps } from 'antd';
import type { RangePickerProps } from 'antd/es/date-picker';
import React, { useEffect, useState, useCallback } from 'react';
import moment from 'moment'; // 引入moment处理日期
import { getitemList, getcompany, additem, getitem, deleteitem, recoveritem } from '../../api/item';

const { Search } = Input;
const { RangePicker } = DatePicker;
const { Title } = Typography;

// 定义类型接口
interface DataType {
  id: string;
  companyid: string;
  account: string;
  title: string;
  address: string;
  start_time: string;
  end_time: string;
  [key: string]: any;
}

interface CompanyType {
  id: string;
  name: string;
}

interface AccountType {
  id: string;
  account: string;
}

interface ItemFormValues {
  id?: string;
  company_id: string;
  company_name?: string;
  title: string;
  address: string;
  period: [moment.Moment | null, moment.Moment | null] | null; // 修改为Moment类型
  start_time?: string;
  end_time?: string;
  account_ids?: string[];
  operator_account: string;
  operator_password: string;
  accountant_account: string;
  accountant_password: string;
  manager_account: string;
  manager_password: string;
  personal_social_base: number | null;
  company_social_base: number | null;
}

interface ItemDetailType {
  id: string;
  companyid: string;
  title: string;
  address: string;
  start_time: string;
  end_time: string;
  gr_security: string;
  dw_security: string;
  account?: AccountType[];
  [key: string]: any;
}

// 账号类型常量
const ACCOUNT_TYPES = {
  ACCOUNTANT: 1, // 会计/劳资员
  MANAGER: 2, // 项目经理
  OPERATOR: 3, // 操作员
};

// 空账号对象，用于默认值
const EMPTY_ACCOUNT: AccountType = { id: '', account: '' };

const ItemPage: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [data, setData] = useState<DataType[]>([]);
  const [recycleData, setRecycleData] = useState<DataType[]>([]);
  const [loading, setLoading] = useState(false);
  const [recycleLoading, setRecycleLoading] = useState(false);
  const [recycleVisible, setRecycleVisible] = useState(false);
  const [recycleCount, setRecycleCount] = useState(0);
  const [form] = Form.useForm<ItemFormValues>();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState<'add' | 'edit'>('add');
  const [companies, setCompanies] = useState<CompanyType[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [recycleSearchValue, setRecycleSearchValue] = useState('');

  // 分页状态
  const [pagination, setPagination] = useState<PaginationProps>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条记录`,
  });

  const [recyclePagination, setRecyclePagination] = useState<PaginationProps>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条记录`,
  });

  // 获取公司列表数据
  const fetchCompanyList = useCallback(async () => {
    try {
      const res: any = await getcompany({});
      if (res && res.code === 1 && res.data) {
        setCompanies(
          res.data.map((item: any) => ({
            id: item.id,
            name: item.account,
          })),
        );
      } else {
        message.error(res?.msg || '获取公司列表失败');
      }
    } catch (error) {
      console.error('获取公司列表失败:', error);
      message.error('获取公司列表失败');
    }
  }, []);

  // 获取项目列表数据
  const fetchItemList = useCallback(async () => {
    setLoading(true);
    try {
      const res: any = await getitemList({
        name: searchValue.trim() || undefined, // 传递搜索关键词
        status: 0,
        page: pagination.current,
        pageSize: pagination.pageSize,
      });

      if (res && res.code === 1) {
        setData(res.data || []);
        setPagination((prev) => ({ ...prev, total: res.total || 0 }));
      } else {
        message.error(res?.msg || '获取项目列表失败');
      }
    } catch (error) {
      console.error('获取项目列表失败:', error);
      message.error('获取项目列表失败');
    } finally {
      setLoading(false);
    }
  }, [searchValue, pagination.current, pagination.pageSize]);


   // 获取回收站数据
  const fetchRecycleList = useCallback(async () => {
    setRecycleLoading(true);
    try {
      const res: any = await getitemList({
        status: 1,
        name: recycleSearchValue.trim() || undefined, // 传递搜索关键词
        page: recyclePagination.current,
        pageSize: recyclePagination.pageSize,
      });

      if (res && res.code === 1) {
        setRecycleData(res.data || []);
        // 确保正确设置回收站计数
        const totalCount = res.total || (res.data ? res.data.length : 0);
        setRecycleCount(totalCount);
        setRecyclePagination((prev) => ({ ...prev, total: totalCount }));
      } else {
        message.error(res?.msg || '获取回收站列表失败');
        setRecycleCount(0); // 出错时设置为0
      }
    } catch (error) {
      console.error('获取回收站列表失败:', error);
      message.error('获取回收站列表失败');
      setRecycleCount(0); // 出错时设置为0
    } finally {
      setRecycleLoading(false);
    }
  }, [recycleSearchValue, recyclePagination.current, recyclePagination.pageSize]);

  useEffect(() => {
    fetchItemList();
    fetchRecycleList();
    fetchCompanyList();
  }, [fetchItemList, fetchRecycleList, fetchCompanyList]);

   // 搜索防抖处理
  const handleSearch = useCallback(
    debounce((value: string) => {
      setSearchValue(value || ''); // 确保空值也被正确处理
      setPagination((prev) => ({ ...prev, current: 1 }));
    }, 300),
    [],
  );

  // 回收站搜索防抖处理
  const handleRecycleSearch = useCallback(
    debounce((value: string) => {
      setRecycleSearchValue(value || ''); // 确保空值也被正确处理
      setRecyclePagination((prev) => ({ ...prev, current: 1 }));
    }, 300),
    [],
  );

  // 打开新增弹窗
  const handleAdd = () => {
    setModalType('add');
    form.resetFields();
    form.setFieldsValue({
      operator_account: '',
      operator_password: '',
      accountant_account: '',
      accountant_password: '',
      manager_account: '',
      manager_password: '',
      account_ids: [],
      personal_social_base: 0,
      company_social_base: 0,
      period: null // 初始化为null
    });
    setIsModalVisible(true);
  };

  // 打开编辑弹窗 - 修复日期处理
  const handleEdit = async (record: DataType) => {
    setModalType('edit');
    form.resetFields(); // 先重置表单
    try {
      setLoading(true);
      const res: any = await getitem({ id: record.id });
      
      if (res && res.code === 1 && res.data) {
        const detail: ItemDetailType = res.data;
        
        // 确保account是数组，避免undefined
        const accounts = Array.isArray(detail.account) ? detail.account : [];
        
        // 安全获取账号信息，使用空对象作为默认值
        const laborAccount = accounts[0] || { ...EMPTY_ACCOUNT }; // 劳资员/操作员
        const accountant = accounts[1] || { ...EMPTY_ACCOUNT };   // 会计
        const manager = accounts[2] || { ...EMPTY_ACCOUNT };      // 项目经理

        // 找到对应的公司名称
        const company = companies.find((c) => c.id === detail.companyid);
        
        // 处理日期格式 - 转换为Moment对象
        const formatDate = (dateString?: string) => {
          if (!dateString) return null;
          // 确保日期格式正确并转换为Moment对象
          const date = moment(dateString.includes('T') ? dateString.split('T')[0] : dateString);
          return date.isValid() ? date : null;
        };

        const startDate = formatDate(detail.start_time);
        const endDate = formatDate(detail.end_time);

        // 填充表单数据 - 确保period是Moment对象数组
        form.setFieldsValue({
          id: record.id,
          company_id: detail.companyid || '',
          company_name: company?.name || '',
          title: detail.title || '',
          address: detail.address || '',
          period: (startDate && endDate) ? [startDate, endDate] : null,
          account_ids: [laborAccount.id, accountant.id, manager.id],
          operator_account: laborAccount.account || '',
          accountant_account: accountant.account || '',
          manager_account: manager.account || '',
          operator_password: '',
          accountant_password: '',
          manager_password: '',
          personal_social_base: detail.gr_security ? Number(detail.gr_security) || 0 : 0,
          company_social_base: detail.dw_security ? Number(detail.dw_security) || 0 : 0,
        });
        setIsModalVisible(true);
      } else {
        message.error(res?.msg || '获取项目详情失败');
      }
    } catch (error) {
      console.error('获取项目详情失败:', error);
      message.error('获取项目详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 下架项目
  const handleRemove = (record: DataType) => {
    Modal.confirm({
      title: '确定要下架该项目吗？',
      content: '下架后项目将移至回收站',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res: any = await deleteitem({ id: record.id });
          if (res && res.code === 1) {
            message.success('项目下架成功');
            fetchItemList();
            fetchRecycleList();
          } else {
            message.error(res?.msg || '项目下架失败');
          }
        } catch (error) {
          console.error('下架项目失败:', error);
          message.error('项目下架失败');
        }
      },
    });
  };

  // 打开回收站弹窗
  const openRecycleBin = () => {
    setRecycleVisible(true);
    fetchRecycleList();
  };

  // 关闭回收站弹窗
  const closeRecycleBin = () => {
    setRecycleVisible(false);
  };

  // 恢复项目
  const handleRestore = (record: DataType) => {
    Modal.confirm({
      title: '确定要恢复该项目吗？',
      content: '恢复后项目将重新显示在项目列表中',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res: any = await recoveritem({ id: record.id });
          if (res && res.code === 1) {
            message.success('项目恢复成功');
            fetchItemList();
            fetchRecycleList();
          } else {
            message.error(res?.msg || '项目恢复失败');
          }
        } catch (error) {
          console.error('恢复项目失败:', error);
          message.error('恢复项目失败');
        }
      },
    });
  };


  // 关闭新增/编辑弹窗
  const handleModalCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  // 监听公司选择变化，自动设置公司名称
  const handleCompanyChange = (companyId: string) => {
    const company = companies.find((c) => c.id === companyId);
    form.setFieldsValue({
      company_name: company?.name || '',
    });
  };

  // 提交表单 - 修复日期处理
  const handleFinish: FormProps<ItemFormValues>['onFinish'] = async (values) => {
    try {
      // 处理日期格式，确保是 YYYY-MM-DD 格式
      let startTime = '';
      let endTime = '';

      if (values.period && values.period.length === 2) {
        // 确保使用Moment对象的format方法
        if (values.period[0]?.isValid()) {
          startTime = values.period[0].format('YYYY-MM-DD');
        }
        if (values.period[1]?.isValid()) {
          endTime = values.period[1].format('YYYY-MM-DD');
        }
      }

      // 基础表单数据
      const formData: any = {
        companyid: values.company_id,
        title: values.title,
        address: values.address,
        start_time: startTime,
        end_time: endTime,
        gr_security: values.personal_social_base?.toString() || '0',
        dw_security: values.company_social_base?.toString() || '0',
      };

      // 处理账号和密码（数组格式，与接口要求一致）
      formData.account = [
        values.operator_account || '', // 操作员账号
        values.accountant_account || '', // 会计账号
        values.manager_account || '', // 项目经理账号
      ];

      // 密码数组：不编辑的传空字符串
      formData.password = [
        values.operator_password || '',
        values.accountant_password || '',
        values.manager_password || '',
      ];

      // 新增时需要传递项目类型数组
      if (modalType === 'add') {
        formData.project_type = [
          ACCOUNT_TYPES.OPERATOR,
          ACCOUNT_TYPES.ACCOUNTANT,
          ACCOUNT_TYPES.MANAGER,
        ];
      }

      // 编辑时需要传递项目ID和账号ID数组
      if (modalType === 'edit' && values.id) {
        formData.projectid = values.id;
        formData.id = values.account_ids; // 账号ID数组
      }

      const res: any = await additem(formData);
      if (res && res.code === 1) {
        message.success(modalType === 'add' ? '新增项目成功' : '编辑项目成功');
        setIsModalVisible(false);
        form.resetFields();
        fetchItemList();
      } else {
        message.error(res?.msg || (modalType === 'add' ? '新增项目失败' : '编辑项目失败'));
      }
    } catch (error) {
      console.error(modalType === 'add' ? '新增项目失败:' : '编辑项目失败:', error);
      message.error(modalType === 'add' ? '新增项目失败' : '编辑项目失败');
    }
  };

  // 处理分页变化
  const handleTableChange: TableProps<DataType>['onChange'] = (pagination) => {
    setPagination({
      ...pagination,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条记录`,
    });
  };

  // 处理回收站分页变化
  const handleRecycleTableChange: TableProps<DataType>['onChange'] = (pagination) => {
    setRecyclePagination({
      ...pagination,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条记录`,
    });
  };

  // 防抖函数
  function debounce<T extends (...args: any[]) => any>(
    func: T,
    wait: number,
  ): (...args: Parameters<T>) => void {
    let timeout: NodeJS.Timeout | null = null;
    return function (...args: Parameters<T>): void {
      if (timeout) {
        clearTimeout(timeout);
      }
      timeout = setTimeout(() => {
        func.apply(this, args);
        timeout = null;
      }, wait);
    };
  }

  // 表格列定义
  const columns: TableProps<DataType>['columns'] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      align: 'center',
    },
    {
      title: '项目名称',
      dataIndex: 'title',
      key: 'title',
      width: 160,
      align: 'center',
    },
    {
      title: '公司标识',
      dataIndex: 'companyid',
      key: 'companyid',
      align: 'center',
    },
    {
      title: '公司名称',
      dataIndex: 'account',
      key: 'account',
      align: 'center',
    },
    {
      title: '项目地址',
      dataIndex: 'address',
      key: 'address',
      align: 'center',
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      key: 'start_time',
      align: 'center',
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      key: 'end_time',
      align: 'center',
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            danger
            size="small"
            icon={<DeleteOutlined />}
            onClick={() => handleRemove(record)}
          >
            下架
          </Button>
        </Space>
      ),
    },
  ];

  // 回收站表格列定义
  const recycleColumns: TableProps<DataType>['columns'] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      align: 'center',
    },
    {
      title: '项目名称',
      dataIndex: 'title',
      key: 'title',
      width: 160,
      align: 'center',
    },
    {
      title: '公司标识',
      dataIndex: 'companyid',
      key: 'companyid',
      align: 'center',
    },
    {
      title: '公司名称',
      dataIndex: 'account',
      key: 'account',
      align: 'center',
    },
    {
      title: '项目地址',
      dataIndex: 'address',
      key: 'address',
      align: 'center',
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      key: 'start_time',
      align: 'center',
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      key: 'end_time',
      align: 'center',
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            icon={<UndoOutlined />}
            onClick={() => handleRestore(record)}
          >
            恢复
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer style={{ backgroundColor: '#fff', minHeight: 'calc(100vh - 60px)' }}>
      <div style={{ padding: '0 20px' }}>

        {/* 搜索区域 */}
        <div
          className="search-box"
          style={{
            margin: '16px 0',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <Search
            placeholder="请输入项目名称"
            allowClear
            enterButton={<SearchOutlined />}
            onSearch={handleSearch}
            onChange={(e) => handleSearch(e.target.value)}
            style={{ width: 280 }}
          />
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Badge count={recycleCount} showZero>
              <Button type="primary" danger onClick={openRecycleBin}>
                回收站
              </Button>
            </Badge>
            <Button
              type="primary"
              onClick={handleAdd}
              icon={<PlusOutlined />}
              style={{ marginLeft: 16 }}
            >
              新增
            </Button>
          </div>
        </div>

        {/* 项目列表表格 */}
        <div className="table-container">
          <Spin spinning={loading}>
            <Table<DataType>
              columns={columns}
              dataSource={data}
              bordered
              rowKey="id"
              size="middle"
              pagination={pagination}
              onChange={handleTableChange}
              style={{
                fontSize: '13px',
                marginBottom: 16,
              }}
            />
          </Spin>
        </div>
      </div>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={modalType === 'add' ? '新增项目' : '编辑项目'}
        open={isModalVisible}
        onCancel={handleModalCancel}
        footer={null}
        width={800}
        destroyOnClose
      >
        <Form
          form={form}
          onFinish={handleFinish}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          layout="horizontal"
          validateMessages={{
            required: '${label}为必填项',
          }}
        >
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>

          {/* 存储账号ID数组（仅编辑时使用） */}
          <Form.Item name="account_ids" hidden>
            <Input />
          </Form.Item>

          <Form.Item label="项目所属公司" name="company_id" rules={[{ required: true }]}>
            <Select
              showSearch
              placeholder="请选择项目所属公司"
              optionFilterProp="children"
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              options={companies.map((company) => ({
                value: company.id,
                label: company.name,
              }))}
              style={{ width: '100%' }}
              onChange={handleCompanyChange}
            />
          </Form.Item>

          <Form.Item name="company_name" hidden>
            <Input />
          </Form.Item>

          <Form.Item label="项目名称" name="title" rules={[{ required: true }]}>
            <Input placeholder="请输入项目名称 例：人力资源项目-A" style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item label="项目地址" name="address" rules={[{ required: true }]}>
            <Input placeholder="请输入项目地址" style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item label="项目周期" name="period" rules={[{ required: true }]}>
            <RangePicker
              style={{ width: '100%' }}
              format="YYYY-MM-DD"
              placeholder={['开始日期', '结束日期']}
            />
          </Form.Item>

          <div style={{ marginLeft: '12%', marginTop: 16, marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={11}>
                <Form.Item
                  label="操作员账号"
                  name="operator_account"
                  rules={[{ required: true }]}
                  labelCol={{ span: 12 }}
                  wrapperCol={{ span: 12 }}
                >
                  <Input placeholder="请输入操作员账号" />
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item
                  label="操作员密码"
                  name="operator_password"
                  rules={[{ required: modalType === 'add' }]}
                  labelCol={{ span: 12 }}
                  wrapperCol={{ span: 12 }}
                >
                  <Input.Password
                    placeholder={modalType === 'add' ? '请输入操作员密码' : '不修改请留空'}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16} style={{ marginTop: 16 }}>
              <Col span={11}>
                <Form.Item
                  label="项目会计账号"
                  name="accountant_account"
                  rules={[{ required: true }]}
                  labelCol={{ span: 12 }}
                  wrapperCol={{ span: 12 }}
                >
                  <Input placeholder="请输入项目会计账号" />
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item
                  label="项目会计密码"
                  name="accountant_password"
                  rules={[{ required: modalType === 'add' }]}
                  labelCol={{ span: 12 }}
                  wrapperCol={{ span: 12 }}
                >
                  <Input.Password
                    placeholder={modalType === 'add' ? '请输入项目会计密码' : '不修改请留空'}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16} style={{ marginTop: 16 }}>
              <Col span={11}>
                <Form.Item
                  label="项目经理账号"
                  name="manager_account"
                  rules={[{ required: true }]}
                  labelCol={{ span: 12 }}
                  wrapperCol={{ span: 12 }}
                >
                  <Input placeholder="请输入项目经理账号" />
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item
                  label="项目经理密码"
                  name="manager_password"
                  rules={[{ required: modalType === 'add' }]}
                  labelCol={{ span: 12 }}
                  wrapperCol={{ span: 12 }}
                >
                  <Input.Password
                    placeholder={modalType === 'add' ? '请输入项目经理密码' : '不修改请留空'}
                  />
                </Form.Item>
              </Col>
            </Row>
          </div>

          <Form.Item
            label="个人社保基数"
            name="personal_social_base"
            rules={[{ required: true }, { type: 'number', min: 0, message: '不能为负数' }]}
          >
            <InputNumber
              placeholder="请输入个人社保基数"
              style={{ width: '100%' }}
              min={0}
              step={0.01}
              precision={2}
            />
          </Form.Item>

          <Form.Item
            label="单位社保基数"
            name="company_social_base"
            rules={[{ required: true }, { type: 'number', min: 0, message: '不能为负数' }]}
          >
            <InputNumber
              placeholder="请输入单位社保基数"
              style={{ width: '100%' }}
              min={0}
              step={0.01}
              precision={2}
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 6, span: 18 }} style={{ marginTop: 24 }}>
            <Space>
              <Button onClick={handleModalCancel}>取消</Button>
              <Button type="primary" htmlType="submit">
                {modalType === 'add' ? '新增' : '保存'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 回收站弹窗 */}
      <Modal
        title="回收站"
        open={recycleVisible}
        onCancel={closeRecycleBin}
        footer={null}
        width={1000}
        destroyOnClose
      >
        <div style={{ marginBottom: 16 }}>
          <Search
            placeholder="请输入项目名称"
            allowClear
            enterButton={<SearchOutlined />}
            onSearch={handleRecycleSearch}
            onChange={(e) => handleRecycleSearch(e.target.value)}
            style={{ width: 280 }}
          />
        </div>
        <Spin spinning={recycleLoading}>
          <Table<DataType>
            columns={recycleColumns}
            dataSource={recycleData}
            bordered
            rowKey="id"
            size="middle"
            pagination={recyclePagination}
            onChange={handleRecycleTableChange}
            style={{ fontSize: '13px' }}
          />
        </Spin>
      </Modal>
    </PageContainer>
  );
};

export default ItemPage;
    